<template>
  <el-dialog
    title="分配角色"
    :visible="showRoleDialog"
    :before-close="handleCloseThis"
  >
    <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
    <el-checkbox-group v-model="checkList">
      <!-- 选项 -->
      <el-checkbox v-for="item in allRoles" :key="item.id" :label="item.id">{{
        item.name
      }}</el-checkbox>
    </el-checkbox-group>
    <!-- 控件 -->
    <template #footer>
      <el-row type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="small" @click="handleAssign"
            >确定</el-button
          >
          <el-button size="small" @click="handleCloseThis">取消</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { Component, Vue, Prop, Emit, Watch } from 'vue-property-decorator'
import { getRolesAPI } from '@/api/roles'
import { getUserInfoByIdAPI, assignUserRoleAPI } from '@/api/users'
// import { IPage } from '@/model/interface/request'

@Component({ name: 'AssignRole' })
export default class AssignRole extends Vue {
  @Prop({ required: true }) showRoleDialog!: boolean // 弹层状态
  @Prop({ required: true }) userId!: string // 用户id
  allRoles: any[] = [] // 角色列表
  checkList: string[] = [] // 选中列表

  // 用户id变化时重新获取权限
  @Watch('userId')
  onIdChange(id: string) {
    this.getUserRolesFn(id)
  }

  created() {
    this.getRolesFn()
  }

  // 获取全部角色列表
  async getRolesFn() {
    try {
      const { rows } = await getRolesAPI({ page: 1, pagesize: 999 })
      this.allRoles = rows
    } catch (e) {
      console.log(e)
    }
  }

  // 获取当前用户角色
  async getUserRolesFn(id: string) {
    try {
      const { roleIds } = await getUserInfoByIdAPI(id)
      this.checkList = [...roleIds]
      // console.log(this.checkList)
    } catch (e) {
      console.log(e)
    }
  }

  // 关闭弹层
  @Emit('update:showRoleDialog')
  handleCloseThis() {
    return false
  }

  // 提交
  async handleAssign() {
    try {
      await assignUserRoleAPI({ id: this.userId, roleIds: this.checkList })
      this.$message.success('操作成功')
      this.handleCloseThis()
    } catch (e) {
      this.$message.info(e)
    }
  }
}
</script>
